//
//  VKRecordDetailVC.m
//  V-Learn
//
//  Created by Apple on 2019/3/6.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKRecordDetailVC.h"
#import "ZFTableHeaderView.h"
#import "ZFPlayerControlView.h"
#import <ZFPlayer/ZFPlayer.h>
#import "ZFAVPlayerManager.h"
#import "VKRecordInfoModel.h"
#import "WKHotclockInfoVOListModel.h"

@interface VKRecordDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ZFTableHeaderView *headerViewTwo;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *contentLab;

@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIImageView *footImageView;

//@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *headerImageView;
@end

@implementation VKRecordDetailVC
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT-44) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化控件
    [self setupUI];
    //设置导航控件
    [self setupNavigationBar];

    [self requestImagesData];
}
#pragma mark - 获取图片接口
- (void)requestImagesData{
    //    ImageConfigController/queryBackImage
    __weak typeof(self)weakSelf = self;
    [WYHXNetWorkManager get:WKQueryBackImage_WKURL params:@{} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
//            NSLog(@"%@",responseObj);
            NSDictionary *dic = responseObj[@"data"];
            NSString *clockUpImage = dic[@"clockUpImage"];
            NSString *clockDownImage = dic[@"clockDownImage"];
            //            NSString *recommendImage = dic[@"recommendImage"];
            NSString *upUrlString = [NSString stringWithFormat:@"%@%@",Public_URL,clockUpImage];
            NSString *downurlString = [NSString stringWithFormat:@"%@%@",Public_URL,clockDownImage];
            
            
            [self.footImageView sd_setImageWithURL:[NSURL URLWithString:upUrlString] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                //                UIImage *picture = [UIImage imageNamed:model.picture];
                //                _pictureView.image = picture;
                
                
                CGSize size = image.size;
                
                CGFloat w = size.width;
                
                CGFloat H = size.height;
                
                CGFloat scale = H/w;
                
                // 等比例计算尺寸
                CGFloat pHeight = 150;
                CGFloat pWidth = image.size.width * pHeight / image.size.height;
                
                self.footerView.frame = CGRectMake(0, 0, ScreenW, pWidth+277);
                self.footImageView.frame = CGRectMake(0, 0, ScreenW, pWidth);
                weakSelf.tableView.tableFooterView = self.footerView;
                
            }];
            [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:downurlString] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                CGSize size = image.size;
                
                CGFloat w = size.width;
                
                CGFloat H = size.height;
                
                CGFloat scale = H/w;
                // 等比例计算尺寸
                CGFloat pHeight = 150;
                CGFloat pWidth = image.size.width * pHeight / image.size.height;
                self.headerView.frame = CGRectMake(0, 0, ScreenW, pWidth+277);
                [self.headerImageView remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.right.mas_equalTo(0);
                    make.top.mas_equalTo(10);
                    make.height.mas_equalTo(pWidth);
                }];
                weakSelf.tableView.tableHeaderView = self.headerView;
                
            }];
        }
        [self.tableView reloadData];
    }];
}
- (void)setupUI{
    self.navigationItem.title = @"打卡详情";
    self.headerView = [UIView new];
    self.headerView.frame = CGRectMake(0, 0, ScreenW, 277*kScaleFit);
    
    //
    self.footerView = [UIView new];
    self.footImageView = [[UIImageView alloc] init];
    [self.footerView addSubview:self.footImageView];
    self.footerView.frame = CGRectMake(0, 0, ScreenW, 1);
    self.footImageView.frame = CGRectMake(0, 0, ScreenW, 1);
    
    self.headerView = [UIView new];
    self.headerImageView = [[UIImageView alloc] init];
    [self.headerView addSubview:self.headerImageView];
    self.headerView.frame = CGRectMake(0, 0, ScreenW, 1);
    //    self.headerImageView.frame = CGRectMake(0, 0, ScreenW, 1);
    [self.headerView addSubview:self.headerImageView];
    [self.headerImageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(10);
        make.height.mas_equalTo(1);
    }];
    
    UILabel *titleLab = [UILabel labelWithText:@"但是公司的高度是广东省公司的广东省高速度来开个大帅哥多撒谎个爱好就跟他说噶三公司噶是的刚好是我哥如果黑暗如果坏都干撒降低公司及" andTextColor:rgb(51,51,51) andName:nil andFontSize:15];
    titleLab.numberOfLines = 2;
    titleLab.text = self.model.clockTitle;
    [self.headerView addSubview:titleLab];
    [titleLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(self.headerImageView.mas_bottom).mas_equalTo(5);
    }];
    
    UILabel *descLab = [UILabel labelWithText:@"但是公司的高度是广东省公司的广及" andTextColor:rgb(51,51,51) andName:nil andFontSize:15];
    descLab.text = self.model.clockOrtherTitle;
    descLab.numberOfLines = 1;
    [self.headerView addSubview:descLab];
    
    [descLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(titleLab.mas_bottom).mas_equalTo(8);
    }];
    //创建视频
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.headerViewTwo.coverImageView];
    self.player.controlView = self.controlView;

    self.headerViewTwo.layer.cornerRadius = 5;
    self.headerViewTwo.layer.masksToBounds = YES;
    [self.controlView.landScapeControlView.kuaijinBtn addTarget:self action:@selector(clickKuaiPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.portraitControlView.kuaiButton addTarget:self action:@selector(clickKuaiPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.portraitControlView.playOrPauseBtn addTarget:self action:@selector(clickPalyOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.landScapeControlView.playOrPauseBtn addTarget:self action:@selector(clickPalyOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        self.tableView.scrollsToTop = !isFullScreen;
        
    };
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        
        [self.controlView resetControlView];
        [self.player.currentPlayerManager seekToTime:0 completionHandler:nil];
        self.player.currentPlayerManager.rate = 1.0;
        
    };

    [self.headerView addSubview:self.headerViewTwo];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50;
    [self.view addSubview:self.tableView];
    [self.headerViewTwo makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(descLab.mas_bottom).mas_equalTo(5);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.bottom.mas_equalTo(0);
    }];

    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.controlView.portraitControlView.bgImageView.hidden = YES;
    self.controlView.landScapeControlView.bgImageView.hidden = YES;
    
//    [self.controlView.portraitControlView.bgImageView sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"kaifeng"]];
//    [self.controlView.landScapeControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@"kaifeng"]];

    [self.controlView showTitle:@"" coverURLString:nil fullScreenMode:ZFFullScreenModeLandscape];

    if (self.model.clockInfoVOList.count>0) {
        VKRecordInfoModel *model = self.model.clockInfoVOList[0];
         NSString *urlString = [NSString stringWithFormat:@"%@%@",Public_URL,model.infoFile];
        //处理带中文的url
        NSString *encodeUrlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        self.player.currentPlayerManager.assetURL = [NSURL URLWithString:encodeUrlString];
    }
    

    self.controlView.backgroundColor = [UIColor clearColor];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.player.currentPlayerManager.assetURL = nil;
    self.player = nil;
}
#pragma mark - 竖屏播放或暂停按钮
- (void)clickPalyOrPauseBtn:(UIButton *)sender{
    
    self.player.currentPlayerManager.rate = 1.0;
}
#pragma mark - 播放快进按钮
- (void)clickKuaiPlayBtn:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        self.player.currentPlayerManager.rate = 2.0;
    }else{//第二次是恢复正常
        self.player.currentPlayerManager.rate = 1.0;
    }
}
- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
    }
    return _controlView;
}

- (ZFTableHeaderView *)headerViewTwo {
    if (!_headerViewTwo) {
        _headerViewTwo = [[ZFTableHeaderView alloc] init];
        @weakify(self)
        _headerViewTwo.playCallback = ^{
            @strongify(self)

        };
    }
    return _headerViewTwo;
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat h = CGRectGetMaxY(self.view.frame);

    self.tableView.frame = CGRectMake(0, LBNAVBAR_HEIGHT, self.view.frame.size.width, h-LBNAVBAR_HEIGHT);
    
}
//
//- (BOOL)shouldAutorotate {
//    return self.player.shouldAutorotate;
//}
//
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
//        return UIInterfaceOrientationMaskLandscape;
//    }
//    return UIInterfaceOrientationMaskPortrait;
//}
//
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    if (self.player.isFullScreen) {
//        return UIStatusBarStyleLightContent;
//    }
//    return UIStatusBarStyleDefault;
//}
//
//- (BOOL)prefersStatusBarHidden {
//    return self.player.isStatusBarHidden;
//}
//
//- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
//    return UIStatusBarAnimationSlide;
//}

#pragma mark - 设置导航
- (void)setupNavigationBar{
    UIButton *btn = [[UIButton alloc] init];
    [btn addTarget:self action:@selector(clickRightItemBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:LBImage(@"wk_share") forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 30, 30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    self.contentLab = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:15];
    self.contentLab.numberOfLines = 0;
    if (self.model.clockInfoVOList.count>0) {
        WKHotclockInfoVOListModel *model = self.model.clockInfoVOList[0];
        self.contentLab.text = model.infoContent;
    }

    [cell.contentView addSubview:self.contentLab];
    [self.contentLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(10);
        make.bottom.mas_equalTo(-10);
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
}
#pragma mark - 分享按钮点击事件
- (void)clickRightItemBtn:(UIButton *)sender{
    
    [LWShareService shared].shareBtnClickBlock = ^(NSIndexPath *index) {
        NSInteger tag = index.row;
        [[LWShareService shared] hideSheetView];
        NSString *shareUrl;
        if (self.model.clockInfoVOList.count>0) {
            //&userId=227@17630721477@1561520850728&from=singlemessage
            WKHotclockInfoVOListModel *model = self.model.clockInfoVOList[0];
            shareUrl = [NSString stringWithFormat:@"%@%@&userId=%@",WKDakaDetailShare_WKURL,model.clockId,[UserModel getUserModel].token];
            
        }
        switch (tag) {
            case 0:
            {
                //userid 传内部的  在添加一个token 拼接上
                
                WXWebpageObject *webpageObject = [WXWebpageObject object];
                webpageObject.webpageUrl = shareUrl;
                
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = self.model.clockOrtherTitle;
                
                
                if (self.model.clockInfoVOList.count>0) {
                    WKHotclockInfoVOListModel *model2 = self.model.clockInfoVOList[0];
                    message.description = model2.infoContent;
                    
                    message.title = self.model.clockOrtherTitle;
                    if (self.model.clockInfoVOList.count>0) {
                        WKHotclockInfoVOListModel *model2 = self.model.clockInfoVOList[0];
                        message.description = model2.infoContent;
                        [message setThumbImage:[UIImage imageNamed:@"wanke_logo"]];
                        
                    }
                    
                }
                message.mediaObject = webpageObject;
                
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = NO;
                req.message = message;
                req.scene = WXSceneSession;
                [WXApi sendReq:req];
            }
                break;
            case 1:
            {
                WXWebpageObject *webpageObject = [WXWebpageObject object];
                webpageObject.webpageUrl = shareUrl;
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = self.model.clockOrtherTitle;
                if (self.model.clockInfoVOList.count>0) {
                    WKHotclockInfoVOListModel *model2 = self.model.clockInfoVOList[0];
                    message.description = model2.infoContent;
                    [message setThumbImage:[UIImage imageNamed:@"wanke_logo"]];
                }
                
                message.mediaObject = webpageObject;
                
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = NO;
                req.message = message;
                req.scene = WXSceneTimeline;
                [WXApi sendReq:req];
                
            }
                break;
            default:
                break;
        }
    };
    
    [[LWShareService shared] showInViewController:self];
}

- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}
-(UIImage *) getImageFromURL:(NSString *)fileURL
{
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    return result;
    
}
@end
